﻿using Hangfire;
using Microsoft.Extensions.DependencyInjection;
using ORS.OrderRobot.IOC;
namespace ORS.OrderRobot;
public class HangfireBackgroundWorkerManager : IBackgroundWorkerManager, ISingleton
{
    private readonly IServiceProvider _provider;

    public HangfireBackgroundWorkerManager(IServiceProvider provider)
    {
        _provider = provider;
    }
    public void Register<T>() where T : IBackgroundWorker
    {
        using var scope = _provider.CreateScope();
        var instance = (IBackgroundWorker)scope.ServiceProvider.GetRequiredService(typeof(T));
        var name = instance.Name;
        var type = typeof(T);
        if (instance is ICronWorker cronWorker)
        {
            // 注册周期性任务，使用静态代理方法
            var cron = cronWorker.GetCronExpressionAsync().Result;
            RecurringJob.AddOrUpdate(
                name, 
                () => RunCronWorker(type), 
                cron,
                new RecurringJobOptions
                {
                    TimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time")
                }
            );
        }
        else if (instance is PeriodicBackgroundWorkerBase)
        {
            instance.StartAsync();
        }
        else
        {
            // 注册为一次性任务（可手动触发）
            RecurringJob.AddOrUpdate(name, () => RunStartAsync(type), Cron.Never());
        }
    }

    // 静态代理方法，供表达式树调用
    public static async Task RunCronWorker(Type workerType)
    {
        var provider = ServiceProviderAccessor.Get();
        using var scope = provider.CreateScope();
        var worker = (ICronWorker)scope.ServiceProvider.GetRequiredService(workerType);
        await worker.ExecuteAsync();
    }
    public static async Task RunStartAsync(Type workerType)
    {
        var provider = ServiceProviderAccessor.Get();
        using var scope = provider.CreateScope();
        var worker = (IBackgroundWorker)scope.ServiceProvider.GetRequiredService(workerType);
        await worker.StartAsync();
    }

    public Task StartAllAsync(CancellationToken cancellationToken = default)
    {
        // 启动所有周期性任务（触发一次即可，Hangfire会自动调度）
        // 这里只需确保所有任务已注册，实际调度由Hangfire管理
        return Task.CompletedTask;
    }

    public Task StopAllAsync(CancellationToken cancellationToken = default){
        // 移除所有注册的周期性任务
        // 这里只能通过反射或记录所有注册名实现，这里假设通过AppDomain获取
        var allWorkerTypes = AppDomain.CurrentDomain
            .GetAssemblies()
            .Where(a => !a.IsDynamic)
            .SelectMany(a =>
            {
                try { return a.GetTypes(); }
                catch { return Array.Empty<Type>(); }
            })
            .Where(t => typeof(IBackgroundWorker).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);
        foreach (var workerType in allWorkerTypes)
        {
            var name = workerType.Name;
            RecurringJob.RemoveIfExists(name);
        }
        return Task.CompletedTask;
    }

    public Task StartAsync(string workerName, CancellationToken cancellationToken = default)
    {
        RecurringJob.Trigger(workerName);
        return Task.CompletedTask;
    }

    public Task StopAsync(string workerName, CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }
}
